package top.hekun.study.core.visitor.simple;

import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.FieldVisitor;
import org.objectweb.asm.MethodVisitor;

import static org.objectweb.asm.Opcodes.*;

/**
 * 〈添加字段〉
 *
 * @author: Sakura
 * @date: 2023/5/8
 */
public class MyClassVisitor4 extends ClassVisitor {
    private boolean isFieldPresent;

    public MyClassVisitor4(int apiVersion, ClassVisitor classWriter) {
        super(apiVersion, classWriter);
    }

    @Override
    public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
        System.out.println("MyClassVisitor4:visit");
        super.visit(version, access, name, signature, superName, interfaces);
    }

    @Override
    public FieldVisitor visitField(int access, String name, String descriptor, String signature, Object value) {
        System.out.println("MyClassVisitor4:visitField -- " + name);
        if (name.equals("var")) {
            isFieldPresent = true;
        }

        return super.visitField(access, name, descriptor, signature, value);
    }

    @Override
    public MethodVisitor visitMethod(int access, String name, String descriptor, String signature, String[] exceptions) {
        System.out.println("MyClassVisitor4:visitMethod -- " + name + " -- " + descriptor);
        return super.visitMethod(access, name, descriptor, signature, exceptions);
    }

    @Override
    public void visitEnd() {
        System.out.println("MyClassVisitor4:visitEnd");
        // 当 字段不存在的时候
        if (!isFieldPresent) {
            // 添加字段
            // 根据方法调用顺序可知, visitField在visitEnd() 前调用
            FieldVisitor fieldVisitor = super.visitField(ACC_PRIVATE | ACC_STATIC, "var", "Ljava/lang/String;", null, null);
            if (fieldVisitor != null) {
                fieldVisitor.visitEnd();
            }
        }
        super.visitEnd();
    }
}
